package com.youhome.service.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.youhome.common.config.BaiDuConfig;
import com.youhome.service.model.HouseTranslate;
import com.youhome.service.model.Trans;
import com.youhome.service.model.TranslationResult;
import com.youhome.service.service.HouseTranslateService;
import com.youhome.service.service.TranslateService;
import com.youhome.utils.TransApiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.List;

/**
 * Created by chen365 on 2017/9/18.
 */
@Service
public class TranslateServiceImpl implements TranslateService {

    @Autowired
    private BaiDuConfig baiDuConfig;

    @Autowired
    private HouseTranslateService houseTranslateService;

    @Override
    public String trans(String sourceText) {
        if (!StringUtils.isEmpty(sourceText)) {
            ObjectMapper mapper = new ObjectMapper();
            TransApiUtils api = new TransApiUtils(baiDuConfig.getApp_id(), baiDuConfig.getSecurity_key());
            try {
                String object = api.getTransResult(sourceText, "en", "zh");
                //System.err.println("Result====>>"+object.toString());
                Trans trans = mapper.readValue(object, Trans.class);

                StringBuilder sb = new StringBuilder();
                List<TranslationResult> trans_result = trans.getTrans_result();
                for (TranslationResult item : trans_result) {
                    sb.append(item.getDst());
                }
                String transText = sb.toString();

                if (!StringUtils.isEmpty(transText)) {
                    return transText;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public TranslationResult trans(String houseId, String sourceText) {
        TranslationResult translationResult = new TranslationResult();
        translationResult.setSrc(sourceText);  //原文
        HouseTranslate houseTranslate = houseTranslateService.selectByHouseId(houseId);
        if (houseTranslate == null) {
            String transText = trans(sourceText);//翻译
            if (!StringUtils.isEmpty(transText)) {
                translationResult.setDst(transText); //译文
                HouseTranslate record = new HouseTranslate();
                record.setHouseId(houseId);
                record.setTranslate(transText);
                houseTranslateService.insertSelective(record);
            }
        } else {
            translationResult.setDst(houseTranslate.getTranslate()); //译文
        }
        return translationResult;
    }
}
